package algorithm.easy;

import pojo.TreeNode;

import java.util.*;

/**
 * @author 江岸
 * @version V1.0
 * @ClassName: MinDiffInBST783
 * @description: 给你一个二叉搜索树的根节点 root ，返回 树中任意两不同节点值之间的最小差值 。
 * 补充：二叉搜索树的中序遍历是有序的
 * @date 2021/4/1314:28
 * @since V1.0
 */
public class MinDiffInBST783 {

    public Set<Integer> treeSet = new TreeSet<>(Comparator.comparing((o)->o));

    public int minDiffInBST(TreeNode root) {
        order(root);
        Iterator<Integer> it = treeSet.iterator();
        int a=-1;
        int min = Integer.MAX_VALUE;
        while(it.hasNext()){
            int b = it.next();
            if (a!=-1){
                int m = Math.abs(b-a);
                min = Math.min(min,m);
            }
            a = b;
        }
        return min;
    }

    public void order(TreeNode root){
        if (root.left!=null){
            order(root.left);
        }
        treeSet.add(root.val);
        if (root.right!=null){
            order(root.right);
        }
    }
}
